<!--
 * @Author: your name
 * @Date: 2021-11-02 10:20:02
 * @LastEditTime: 2021-11-02 11:17:12
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /websocket/index.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box {
            width: 200px;
            height: 200px;
            position: fixed;
            top: 0;
            left: 0;
            background: pink;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <script>
        const ws = new WebSocket('ws://localhost:9999/');
        console.log(ws)
        // 连接的时候触发
        ws.onopen = function (scoket) {
            if(ws.readyState === 1) {
                console.log('连接成功')
                ws.send('hello')
            }
        }

        // 后端发送消息时候触发
        ws.onmessage = function(msg) {
            const msgObj = JSON.parse(msg.data);
            console.log(msgObj)
            box.style.top = msgObj.top + 'px';
            box.style.left = msgObj.left + 'px';
        }

        box.onmousedown = function (ev) {
            let clix = ev.clientX - this.offsetLeft;
            let cliy = ev.clientY - this.offsetTop;
            document.onmousemove = function(ev) {
                let left = ev.clientX - clix;
                let top = ev.clientY - cliy;
                ws.send(JSON.stringify({
                    left,
                    top
                }))
                box.style.top = top + 'px';
                box.style.left = left + 'px';
                document.onmouseup = function () {
                    document.onmousemove = null;
                    document.onmouseup = null;
                }
            }
        }
    </script>
</body>
</html>